package org.jeecg.modules.phone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.phone.entity.*;
import org.jeecg.modules.phone.enums.EntityEnums;
import org.jeecg.modules.phone.enums.ResourcesEnums;
import org.jeecg.modules.phone.enums.TaskEnums;
import org.jeecg.modules.phone.mapper.*;
import org.jeecg.modules.phone.service.IPhoneEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description: 实体手机管理
 * @Author: jeecg-boot
 * @Date:   2022-08-29
 * @Version: V1.0
 */
@Service
public class PhoneEntityServiceImpl extends ServiceImpl<PhoneEntityMapper, PhoneEntity> implements IPhoneEntityService {
    @Autowired
    PhoneEntityMapper phoneEntityMapper;

    @Autowired
    PhoneTaskChildrenMapper phoneTaskChildrenMapper;

    @Autowired
    PhoneEntityTaskMapper phoneEntityTaskMapper;

    @Autowired
    PhoneEntityCmdMapper phoneEntityCmdMapper;

    @Autowired
    PhoneEntityTaskRsourceMapper phoneEntityTaskRsourceMapper;

    @Value("${server.name}")
    private String  serverName;
    @Override
    public IPage<PhoneEntityVo> searchList(Page<PhoneEntity> page, QueryWrapper<PhoneEntity> queryWrapper) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        String username = loginUser.getUsername();
        queryWrapper.eq("e.create_by",username) ;

        IPage<PhoneEntityVo> phoneEntityVoIPage = phoneEntityMapper.searchList(page, queryWrapper);
        List<PhoneEntityVo> records = phoneEntityVoIPage.getRecords();

        records.forEach(v->{
            if(v.getTag().equals(TaskEnums.TaskType.M.getName())){
                v.setTagName("M");
            }
            if(v.getTag().equals(TaskEnums.TaskType.Z.getName())){
                v.setTagName("Z");
            }

        });
        phoneEntityVoIPage.setRecords(records);
        return  phoneEntityVoIPage;
    }

    @Override
    public void run(List<String> entityList) {
        /*获取该批手机的默认任务，并添加任务，修改手机状态为执行中。*/

        List<PhoneEntity> phoneEntities = phoneEntityMapper.selectList(new QueryWrapper<PhoneEntity>().lambda()
                .eq(PhoneEntity::getEntityStatus, EntityEnums.EntityStatus.ONLINE.getName())
                .in(PhoneEntity::getId, entityList)
        );

        AtomicReference<String> tmp  = new AtomicReference<>("");
        phoneEntities.forEach(v-> {
            tmp.set(tmp + "," + v.getId());
            v.setEntityStatus(EntityEnums.EntityStatus.RUNNING.getName());
            phoneEntityMapper.updateById(v);
        });
        entityList =   Arrays.asList(tmp.get().split(","));
        List<PhoneEntityTaskRsource> phoneEntityTaskRsourcesList = phoneEntityTaskRsourceMapper.selectList(new QueryWrapper<PhoneEntityTaskRsource>().lambda()
                .in(PhoneEntityTaskRsource::getEntityId,entityList)
                .eq(PhoneEntityTaskRsource::getResourceStatus, ResourcesEnums.ResourcesStatus.ENABLED.getName())
        );
//        System.out.println(phoneEntityTaskRsourcesList);
        phoneEntityTaskRsourcesList.forEach(v -> {
            /*获取小任务，并添加到任务里，开始调度*/
            List<PhoneTaskChildren> phoneTaskChildrenList = phoneTaskChildrenMapper.selectList(
                    new QueryWrapper<PhoneTaskChildren>()
                            .eq("parent_task_id", v.getTaskId())
                            .orderByAsc("seq")
            );
            Long currentTimestamp = DateUtils.getCurrentTimestamp() ;  /* 20221013101713 */
            Long currentTimestampMillis =   DateUtils.getMillis()  ;  /*  1665627433601 */

            phoneTaskChildrenList.forEach(x->{
                /* 创建任务表 */
                phoneEntityTaskMapper.insert(new PhoneEntityTask()
                                .setEntityId(v.getEntityId())
                                .setTaskChildrenId(x.getId())
                                .setResourceId(v.getId())
                                .setTaskStatus(TaskEnums.TaskStatus.WAIT.getName())
                                .setId(  currentTimestampMillis    + x.getSeq() )
                );
            });

        });




    }

    @Override
    public void stop(List<String> entityList) {
        /*主要逻辑是把任务停下来，就是把状态都变成取消，手机状态变回在线即可*/

        phoneEntityMapper.update(
                new PhoneEntity().setEntityStatus(EntityEnums.EntityStatus.ONLINE.getName()),
                new QueryWrapper<PhoneEntity>().lambda()
                        .and(v->v.eq(PhoneEntity::getEntityStatus, EntityEnums.EntityStatus.RUNNING.getName())
                                .or().eq(PhoneEntity::getEntityStatus, EntityEnums.EntityStatus.WARN.getName()))
                        .in(PhoneEntity::getId, entityList)
        );
        //设置task为取消

        phoneEntityTaskMapper.update(
                new PhoneEntityTask().setTaskStatus(TaskEnums.TaskStatus.CANCEL.getName()),
                new QueryWrapper<PhoneEntityTask>().lambda()
                        .and(i -> i.eq(PhoneEntityTask::getTaskStatus, TaskEnums.TaskStatus.WAIT.getName())
                                .or().eq(PhoneEntityTask::getTaskStatus, TaskEnums.TaskStatus.RUN.getName()))
                        .in(PhoneEntityTask::getEntityId, entityList)
        );
        //设置这些机的命令为0
        phoneEntityCmdMapper.update(
                new PhoneEntityCmd().setCmdStatus("0"),
                new QueryWrapper<PhoneEntityCmd>().lambda()
                        .in(PhoneEntityCmd::getEntityId, entityList)
        );



    }
}
